using System;
using System.Collections;
using System.Diagnostics;
using System.Drawing;
using System.Windows.Forms;

using Nairo.Parser.Dom;

namespace Nairo
{
	public class HtmlRenderer
	{
		private ArrayList renderUnits;
		private int myTargetWidth;

		private int myWidth;
		public int Width
		{
			get { return myWidth; }
			set { myWidth = value; }
		}

		private int myHeight;
		public int Height
		{
			get { return myHeight; }
			set { myHeight = value; }
		}

		public int TargetWidth
		{
			get { return myTargetWidth; }
			set { myTargetWidth = value; }
		}

		public HtmlRenderer(FileUnit file, int targetwidth)
		{
			myWidth = 0;
			myHeight = 0;
			myTargetWidth = targetwidth;
			renderUnits = new ArrayList();
			renderUnits.Add(new RenderUnit(targetwidth));
		}
		
		public RenderUnit PreviousUnit()
		{
			return renderUnits[renderUnits.Count - 2] as RenderUnit;
		}

		public RenderUnit CurrentUnit()
		{
			return renderUnits[renderUnits.Count - 1] as RenderUnit;
		}

		public RenderUnit NewUnit()
		{
			RenderUnit b = new RenderUnit(myTargetWidth);
			renderUnits.Add(b);
			return b;
		}
		
		public void UpdateRenderer()
		{
			// Calculate unit tops
			int top = 8;
			int width = 0;
			int oldTop = 0;
			
			for (int i = 0; i < this.renderUnits.Count; i++) {
				if ((renderUnits[i] as RenderUnit).GetItemCount() == 0) {
					this.renderUnits.RemoveAt(i);
				}
			}
			
			foreach (RenderUnit unit in renderUnits)
			{
//				top = (unit.FirstItem != null) ? Math.Max(unit.FirstItem.Element.MarginTop, top) : top;
				unit.Top = top;
				
				unit.ComputeItemCoords();
				top += unit.BoxHeight;
				width = Math.Max(width, unit.CurrentWidth);
			}

			this.Height = top;
			this.Width = width;
		}

		public void Paint(Graphics g)
		{
			TextRenderItem.paintCounter = 0;
			
			foreach (RenderUnit band in renderUnits)
			{
				band.Paint(g);
			}
			
			Debug.Print("Painting Count: " + TextRenderItem.paintCounter);
		}

		///         <summary>
		///         Returns the item whose
		///         bounding rectangle contains the specified point.
		///         Used for hyperlink hit-testing.
		///         <summary>
		///         <param name="x"><param>
		///         <param name="y"><param>
		///         <returns><returns>
		public RenderItem LocateItem(int x, int y)
		{
			foreach (RenderUnit band in this.renderUnits)
			{
				if (y >= band.Top)
				{
					if (y <= band.Top + band.Height)
					{
						return band.LocateItem(x, y);
					}
				}
			}
			return null;
		}

		public override string ToString()
		{
			string s = "<HTMLRenderer ";
			foreach (RenderUnit band in renderUnits)
			{
				s += band.ToString();
			}
			s += " HTMLRenderer>";
			return s;
		}


	}
	

}
